package chapter15;

import java.util.ArrayDeque;

/**
 * Created by 蜡笔小新丶 on 2017/10/14.
 */
public class Codes
{
    /**
     * Encode and decode a message using a key of values stored in
     * a queue.
     */
    public static void main ( String[] args) throws Exception {
        int[] key = {5, 12, -3, 8, -9, 4, 10};
        Integer keyValue;
        String encoded = "", decoded = "";
        String message = "All programmers are playwrights and all " +
                "computers are lousy actors.";

        ArrayDeque<Integer> keyQueue1 = new ArrayDeque<>();
        ArrayDeque<Integer> keyQueue2 = new ArrayDeque<Integer>();

        /** load key queue */
        for (int scan=0; scan < key.length; scan++)
        {
            keyQueue1.add (new Integer(key[scan]));
            keyQueue2.add (new Integer(key[scan]));
        }

        /** encode message */
        for (int scan=0; scan < message.length(); scan++)
        {
            keyValue = keyQueue1.remove();
            encoded += (char) ((int)message.charAt(scan) + keyValue.intValue());
            keyQueue1.add (keyValue);
        }

        System.out.println ("Encoded Message:\n" + encoded + "\n");

        /** decode message */
        for (int scan=0; scan < encoded.length(); scan++)
        {
            keyValue = keyQueue2.remove();
            decoded += (char) ((int)encoded.charAt(scan) - keyValue.intValue());
            keyQueue2.add (keyValue);
        }

        System.out.println ("Decoded Message:\n" + decoded);
    }
}